import { createRouter, createWebHistory } from 'vue-router'
// 声明导入的是type
import type { RouterOptions } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/home/index.vue')
    },
    {
      path: '/',
      name: 'root',
      redirect: '/home'
    },
    {
      name: '404',
      path: '/:catchAll(.*)',
      component: () => import(`@/views/error/404.vue`)
    }
  ]
} as RouterOptions)

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  if (to.name === '404' && to.path !== '/404') {
    if (userStore.currentPath !== to.path) {
      next(to.fullPath)
      userStore.setCurrentPath(to.path)
    } else {
      // 当前是404,去到其余页面
      next()
      userStore.setCurrentPath('/404')
    }
  } else {
    // 非刷新页面情况
    next()
    userStore.setCurrentPath(to.path)
  }
})

export default router
